package com.mybatispuls.springboot.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class PayController {

    // 商户appid
    public String APPID = "2016103000778564";
    // 私钥 pkcs8格式的
    public String RSA_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCgH31MMcYsn56Usk37aKvtxinW7ruHEHVLAE8Ma4qX51Z8t+9RjAP7EIhT3XL0FOa7mCE2KgFed/11haXEkAJF0o1HwoEZ66+8fMdBMbJs73hhA4YbbQOsA4k2BHxDLVOdogZxBPM3j514wmMKgvfc+Y/Aglpyb4u/xeu6Q4UQ4F6gc9xcwO63DmZYIc54eppyKAjpQ59g8vsbWgXGNm3kqLn8R+M3V2PRsFnpG+PyDcOxSnJvTBQZMXxDinbVMs978YJ9MwtvfZxkUDOxXyHufxnJfppQvlBtyqZJOi+G2wnu0ZZMxrO4tWKCNHg6/za5ogZ2OlSTj+wqxQ68jNm9AgMBAAECggEAe72aAMX+VgHMdTEN3pnXM9sN/lFjjk8DtcA5VmnNIvLd/WfPg/9mHCF8mQLrkQCOBq7cC5WOlUi5EJcFsc9wUjESiUAgsL1Yg5sSCKm1L0YoiyBEBPHMAqSA5sO0m91tXsYVoEWpB2ju0qG2FCt+DMC3fJe/+euF3d+/+aOwM4dX6zrff0qhDDTu6U/Lcb6QoGdZStlvaUxv6zmjPJ0dQ2VDF5/hULeFa7yz+IeteVeW+ToCcxZtIsaX6r3/fU2FlI2GlUjwuQTVpJPiw80TTn2z3zVtHGDUTkiyn/tjjFrHqREje1ad8rOVw/zWNaQZAPyJL+7Zv60roIsEGodjQQKBgQDLaKsgtlIU2VB1PQzeL+LyNtKJ20Uq1la4OCV7iC9ysTdedRzPB3BMQlqeEi583By2MZwKwVQlhYztiD7oWlbYVC9ZcRkMAPWawujYzzsqSpHixLJrKWv9b0nso/S0TMYNo1LDmPfp5Q2j43AWhfR4igbt9ePCAe6BASaOq5Tu+QKBgQDJhctT023jkSSq8gYlDpCCCJrt2kAdSJtivnCMB8dNh3q/JspjT239sZhQziTiCoClFbrchK/7eGEQU8PtiCsOjE0BzGzIlBRsIsajqZRMGKoq6cdcQz53RWet/GyjK50g6XC/ffwh8ZI/6+Djntmtxd/ElLfwCZ/TKMbdIB/95QKBgDuHim2sbiFD6FQnZdiw0w5oFP3bekarK/4GEJIyrRA35ShzxdahKrBmyvZwA8Lu+EgqBKzxH5tLlo79zMtbhQcSvDjE7LuinD6KxHKPU5Vw9XkUb9ME8GHfbBchdMA/p8beAZ7U6dk9+9v2+BrfYUjVvGlwCRQCVLbUi2A9vvyhAoGAUN/F6r02I5azLXt1pdeDfPvxGTV2d4oU+frNdhUFEgMl6qKppFNTI/Xq17rzKFfoqtfepvMFIRl9cqz7O09jYDJEEU219oUe8Qq/xxyeLC/V0uUBIfDGl90dr8BW5ODy7StiGSd5UTH+bHLATPkKCOgZVm4Mp2NlZbu+my1ySVUCgYAAl4JBfUBuEtZNOnyNfBBOEl3GkwIHoXXTOnk00WXWHxGxFafNS/Ny2z2sk9Bp3U10feWuiQTJFafxAjsBEyglpEKZPuY3eUkq0UenvtOj/AjUipon/C90cXjLprXIC1eiqddJ6/sI2XehfyFEWTBIYz9YY6sj8bic0nPu4J257w==";
    // 服务器异步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public String notify_url = "http://t4yf9w.natappfree.cc/notify";
    // 页面跳转同步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 商户可以自定义同步跳转地址
    public String return_url = "http://t4yf9w.natappfree.cc/return";
    // 请求网关地址
    public String URL = "https://openapi.alipaydev.com/gateway.do";
    // 编码
    public String CHARSET = "UTF-8";
    // 返回格式
    public String FORMAT = "json";
    // 支付宝公钥
    public String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx14IX2LBufcZkATwivFcyfARKCoFtMRfOHyyU+HSBQpeQk5iHRAGaxqHhxnwT1YBxjRtBRW4MSAAPS/XOM0sNHnIIn3MWSchcS0bV3ZAPHHtqAWLJHaqoRG7FuATloMm73CmoWEZGWKc9n8CIredmVlAcmdSDB2u/vUCWUefL3ludxMmeI0MGlK02aL7nMiNE2bCkhFA1z624JB5MTy8AyEi2M/b5yYJyfQj8HfyanUMDS/wp544Ff37+/Z3CMWg60/jzAsYgjlIlHqo9NMHULAiuTscd0O/GpddRS9+D8I4qyUq8pMu+37AfAV8FZfRfPP8/NpCVsu8TCiW0CcfVQIDAQAB";
    // 日志记录目录
    public String log_path = "/log";
    // RSA2
    public String SIGNTYPE = "RSA2";

    @RequestMapping("pay")
    @ResponseBody
    public String doPost(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse) throws ServletException, IOException {
        AlipayClient alipayClient = new DefaultAlipayClient(URL, APPID, RSA_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGNTYPE); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        //AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        /*model.setOutTradeNo();
        model.setTotalAmount();
        model.setSubject();
        model.setProductCode();*/
        //alipayRequest.setBizModel(model);
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url); //在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":\"20150421410203123\"," +
                " \"total_amount\":\"88.88\"," +
                " \"subject\":\"女朋友\"," +
                        "\"product_code\":\"FAST_INSTANT_TRADE_PAY\""+
//                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
//        httpResponse.setContentType("text/html;charset=" + CHARSET);
//        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
        //return "index";
        return form;
    }

    @RequestMapping("/notify")
    @ResponseBody
    public void notifyUrlMethod(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        System.out.println(requestParams);
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                ALIPAY_PUBLIC_KEY,
                CHARSET,
                SIGNTYPE); //调用SDK验证签名

        System.out.println(signVerified);

        //——请在这里编写您的程序（以下代码仅作参考）——

		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

//            logger.info("out_trade_no="+out_trade_no);
//            logger.info("trade_no="+trade_no);
//            logger.info("trade_status="+trade_status);
            System.out.println("out_trade_no="+out_trade_no);
            System.out.println("trade_no="+trade_no);
            System.out.println("trade_status="+trade_status);

        }else {//验证失败
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);

//            logger.info("验证失败");
            System.out.println("验证失败");
        }

    }

    @ResponseBody
    @RequestMapping("/return")
    public String returnUrlMethod(HttpServletRequest request, HttpSession session) throws AlipayApiException, UnsupportedEncodingException {
        // 获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        System.out.println(requestParams);
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                ALIPAY_PUBLIC_KEY,
                CHARSET,
                SIGNTYPE); //调用SDK验证签名
        System.out.println(signVerified);

        // ——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            // 商户订单号
            String orderNum = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // 支付宝交易号
            String payOrderNum = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // 付款金额
            String orderAmount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            // 保存到数据库
            // 1.从Session域中获取OrderVO对象
            //OrderVO orderVO = (OrderVO) session.getAttribute("orderVO");

            // 2.将支付宝交易号设置到OrderVO对象中
            //orderVO.setPayOrderNum(payOrderNum);

            // 3.发送给MySQL的远程接口
            //ResultEntity<String> resultEntity = mySQLRemoteService.saveOrderRemote(orderVO);
            //logger.info("Order save result="+resultEntity.getResult());

            return "trade_no:"+payOrderNum+"<br/>out_trade_no:"+orderNum+"<br/>total_amount:"+orderAmount;
        }else {

            // 页面显示信息：验签失败
            return "验签失败";

        }
    }

}
